<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of userProfileController
 *
 * @author usuario
 */
class User_UserProfileController extends Model3_Controller
{

    public function init()
    {
        if (!Model3_Auth::isAuth())
        {
            $this->redirect('Index/index');
        }
        
        $credentials = Model3_Auth::getCredentials();
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        /* @var $em Doctrine\ORM\EntityManager */


        $user = $em->find('DefaultDb_Entities_User', $credentials['id']);
        $this->view->user = $user;
    }

    public function indexAction()
    {
        $this->view->getJsManager()->addJs('jquery/jquery.validate.js');
        $this->view->getJsManager()->addJs('application/User/UserProfile/validateProfile.js');
        
        $this->view->error = false;
        $credentials = Model3_Auth::getCredentials();
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        if ($this->getRequest()->isPost())
        {
            $user = $em->find('DefaultDb_Entities_User', $credentials['id']);
            $post = $this->getRequest()->getPost();
            $user->setFirstName($post['firstName']);
            $user->setLastName($post['lastName']);
            $user->setTitle($post['title']);
            $user->setCommercialName($post['commercialName']);
            $user->setDayInvoice($post['dateInvoice']);
            $user->setCellPhone($post['cellPhone']);
            $user->setLocalNumber($post['localNumber']);
            $em->persist($user);
            $em->flush();
            $this->view->resp = true;
        }
    }

    public function passwordAction()
    {
        $this->view->error = false;
        $credentials = Model3_Auth::getCredentials();
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        if ($this->getRequest()->isPost())
        {
            $user = $em->find('DefaultDb_Entities_User', $credentials['id']);
            $post = $this->getRequest()->getPost();
            if (md5($post['passOld']) == $user->getPassword())
            {
                if ($post['passNew'] == $post['passRepeat'])
                {
                    $user->setPassword(md5($post['passNew']));
                    $em->persist($user);
                    $em->flush();
                    $this->view->resp = true;
                }
                else
                    $this->view->error = "La confirmacion es incorrecta";
            }
            else
                $this->view->error = "La contrase&ntilde;a es incorrecta";
        }
    }

}

?>
